package com.example.demo2jsp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", value = "/loginServlet")
public class HelloServlet extends HttpServlet {
    private String message;

    public void init() {
        System.out.println("生命周期函数init");
        message = "Hello World!";
    }

//    微信官方文档1（用于：获取token）  https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
//    微信官方文档2（用于：获取个人信息） https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Official_Accounts/official_account_website_authorization.html

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        String code = request.getParameter("code");
        System.out.println("code:"+code);

        String APPID="wx7287a60bb700fd21";
        String secret = "1ef8755f92bebae8ad7bab432ba29cbf";


        String SendUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid="+APPID+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        HttpClient httpclient = null;
        GetMethod post = null;
        try {
            httpclient = new HttpClient();
            post = new GetMethod(SendUrl);
            //设置编码方式
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            //添加参数
            // post.addParameter("order", order);
            //执行
            httpclient.executeMethod(post);
            //接口返回信息
            String info = new String(post.getResponseBody(), "UTF-8");
            System.out.println("返回结果："+info);

            JSONObject obj = JSON.parseObject(info);

            // 2.根据，继续请求个人信息
            String SendUrl2 ="https://api.weixin.qq.com/sns/userinfo?" +
                    "access_token="+obj.get("access_token")+"&openid="+obj.get("openid")+"&lang=zh_CN";
            GetMethod getM = null;
            getM = new GetMethod(SendUrl2);
            //执行
            httpclient.executeMethod(getM);
            //接口返回信息
            String info2 = new String(getM.getResponseBody(), "UTF-8");
            System.out.println("返回结果2："+info2);

            JSONObject obj2 = JSON.parseObject(info2);

            HttpSession session = request.getSession();
            session.setAttribute("nickname", obj2.get("nickname"));
            session.setAttribute("headimgurl", obj2.get("headimgurl"));

            // 重定向到其他页面
            response.sendRedirect("login.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接，释放资源
            post.releaseConnection();
            ((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown();
        }

        // Hello
//        PrintWriter out = response.getWriter();
//        out.println("<html><body>");
//        out.println("<h1>" + message + "</h1>");
//        out.println("</body></html>");
    }

    public void destroy() {
    }
}